import React, { useState, useEffect } from 'react';
import { getToken } from '../login/loginApi';
import { getPromptList, createPrompt, updatePrompt, deletePrompt, getPromptById } from './promptApi';
import Pagination from '../Pagination'; // 引入分页组件

const Prompt: React.FC = () => {
  const [promptData, setPromptData] = useState<any>({
    data: {
      pageIndex: 1,
      pageSize: 10,
      prompt: [],
      total: 0
    },
    status: ''
  });

  const [newPromptData, setNewPromptData] = useState<any>({
    content: "",
    keywords: "",
    settings: ""
  });

  const [updatePromptData, setUpdatePromptData] = useState<any>({
    id: "",
    content: "",
    keywords: "",
    settings: ""
  });

  const [showNewPromptModal, setShowNewPromptModal] = useState(false);
  const [showUpdatePromptModal, setShowUpdatePromptModal] = useState(false);

  useEffect(() => {
    loadPromptList();
  }, []);

  const loadPromptList = async () => {
    try {
      const response = await getPromptList();
      setPromptData(response);
    } catch (error) {
      console.error('Error fetching prompts:', error);
    }
  };

  const handleCreatePrompt = async () => {
    try {
      await createPrompt(newPromptData);
      loadPromptList();
      setShowNewPromptModal(false);
    } catch (error) {
      console.error('Error creating prompt:', error);
    }
  };

  const handleUpdatePrompt = async (id: string) => {
    try {
      const prompt = await getPromptById(id);
      setUpdatePromptData(prompt.data);
      setShowUpdatePromptModal(true);
    } catch (error) {
      console.error('Error fetching prompt for update:', error);
    }
  };

  const handleConfirmUpdate = async () => {
    try {
      await updatePrompt(updatePromptData);
      loadPromptList();
      setShowUpdatePromptModal(false);
    } catch (error) {
      console.error('Error updating prompt:', error);
    }
  };

  const handleDeletePrompt = async (id: string) => {
    try {
      await deletePrompt(id);
      loadPromptList();
    } catch (error) {
      console.error('Error deleting prompt:', error);
    }
  };

  const handlePreviousPage = () => {
    if (promptData.data.pageIndex > 1) {
      setPromptData((prev: { data: { pageIndex: number; }; }) => ({ ...prev, data: { ...prev.data, pageIndex: prev.data.pageIndex - 1 } }));
      loadPromptList();
    }
  };

  const handleNextPage = () => {
    if (promptData.data.pageIndex * promptData.data.pageSize < promptData.data.total) {
      setPromptData((prev: { data: { pageIndex: number; }; }) => ({ ...prev, data: { ...prev.data, pageIndex: prev.data.pageIndex + 1 } }));
      loadPromptList();
    }
  };

  return (
    <div className="p-4">
      <h1 className="text-3xl font-bold mb-4">prompt管理</h1>
      <button className="bg-blue-500 text-white px-4 py-2 rounded mb-4" onClick={() => setShowNewPromptModal(true)}>新建</button>
      {showNewPromptModal && (
        <div className="fixed top-0 left-0 w-full h-full flex items-center justify-center bg-black bg-opacity-50">
          <div className="bg-white p-6 rounded-lg shadow-lg">
            <h2 className="text-xl font-bold mb-4">新建提示</h2>
            <input className="w-full mb-2 p-2 border border-gray-300 rounded-md" type="text" placeholder="内容" value={newPromptData.content} onChange={(e) => setNewPromptData({ ...newPromptData, content: e.target.value })} />
            <input className="w-full mb-2 p-2 border border-gray-300 rounded-md" type="text" placeholder="关键词" value={newPromptData.keywords} onChange={(e) => setNewPromptData({ ...newPromptData, keywords: e.target.value })} />
            <input className="w-full mb-2 p-2 border border-gray-300 rounded-md" type="text" placeholder="语言设定" value={newPromptData.settings} onChange={(e) => setNewPromptData({ ...newPromptData, settings: e.target.value })} />
            <button className="bg-blue-500 text-white px-4 py-2 rounded mr-2" onClick={handleCreatePrompt}>确认新建</button>
            <button className="bg-gray-500 text-white px-4 py-2 rounded" onClick={() => setShowNewPromptModal(false)}>取消</button>
          </div>
        </div>
      )}
      {showUpdatePromptModal && (
        <div className="fixed top-0 left-0 w-full h-full flex items-center justify-center bg-black bg-opacity-50">
          <div className="bg-white p-6 rounded-lg shadow-lg">
            <h2 className="text-xl font-bold mb-4">更新提示</h2>
            <input className="w-full mb-2 p-2 border border-gray-300 rounded-md" type="text" placeholder="ID" value={updatePromptData.id} readOnly />
            <input className="w-full mb-2 p-2 border border-gray-300 rounded-md" type="text" placeholder="内容" value={updatePromptData.content} onChange={(e) => setUpdatePromptData({ ...updatePromptData, content: e.target.value })} />
            <input className="w-full mb-2 p-2 border border-gray-300 rounded-md" type="text" placeholder="关键词" value={updatePromptData.keywords} onChange={(e) => setUpdatePromptData({ ...updatePromptData, keywords: e.target.value })} />
            <input className="w-full mb-2 p-2 border border-gray-300 rounded-md" type="text" placeholder="语言设定" value={updatePromptData.settings} onChange={(e) => setUpdatePromptData({ ...updatePromptData, settings: e.target.value })} />
            <button className="bg-blue-500 text-white px-4 py-2 rounded mr-2" onClick={handleConfirmUpdate}>确认更新</button>
            <button className="bg-gray-500 text-white px-4 py-2 rounded" onClick={() => setShowUpdatePromptModal(false)}>取消</button>
          </div>
        </div>
      )}
      <table className="w-full">
        <thead>
          <tr className="bg-gray-200">
            <th className="p-2">ID</th>
            <th className="p-2">内容</th>
            <th className="p-2">关键词</th>
            <th className="p-2">语言设定</th>
            <th className="p-2">创建时间</th>
            <th className="p-2">更新时间</th>
            <th className="p-2">操作</th>
          </tr>
        </thead>
        <tbody>
          {promptData.data.prompt.map((prompt: any) => (
            <tr key={prompt.id} className="border-b">
              <td className="p-2">{prompt.id}</td>
              <td className="p-2">{prompt.content}</td>
              <td className="p-2">{prompt.keywords}</td>
              <td className="p-2">{prompt.settings}</td>
              <td className="p-2"> {new Date(prompt.created_at).toLocaleString()}</td>
              <td className="p-2"> {new Date(prompt.created_at).toLocaleString()}</td>

              <td className="p-2">
                <button className="bg-green-500 text-white px-2 py-1 rounded mr-2" onClick={() => handleUpdatePrompt(prompt.id)}>更新</button>
                <button className="bg-red-500 text-white px-2 py-1 rounded" onClick={() => handleDeletePrompt(prompt.id)}>删除</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    <Pagination
        pageIndex={promptData.data.pageIndex}
        total={promptData.data.total}
        pageSize={promptData.data.pageSize}
        handlePreviousPage={handlePreviousPage}
        handleNextPage={handleNextPage}
      />
    </div>
  );
};

export default Prompt;